/*
* Conditions Of Use
*
* This software was developed by employees of the Sigmatrix(Beijing) Corporation.
* This software is provided by sigmatrix as a service and is expressly
* provided "AS IS."  Sigmatrix MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY.  Sigmatrix does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement.
*
*/
package com.sigmatrix.h5.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.sigmatrix.h5.dao.ProductDao;
import com.sigmatrix.h5.dto.ProductData;
import com.sigmatrix.h5.entity.Product;
import com.sigmatrix.h5.exception.DaoException;
import com.sigmatrix.h5.utils.Cons;
import com.sigmatrix.h5.utils.Utils;
import com.sigmatrix.sc.jdbc.common.dao.DaoImpl;

/**
 *@ClassName: ProductDaoImpl
 *@Description:
 *@author MH
 *@date 2017年8月18日 上午11:37:08
 */
@Repository(value = "productDao")
public class ProductDaoImpl extends DaoImpl<Product,Integer> implements ProductDao{
	
	/**表名*/
	public static final String TABLE_NAME = "_product";
	

	/**(non-Javadoc)
	 *@Title: findByBasicModuleId
	 *@Description: 
	 *@see com.sigmatrix.sc.distribution.rebate.inter.dao.ProductDao#findByBasicModuleId(java.lang.Integer)
	 *@author MH
	 *@date 2017年8月18日 上午11:44:56
	 */
	@Override
	public Product findByBasicModuleId(Integer basicModuleId) {
		Product vo = new Product();
		vo.setBasicModuleId(basicModuleId);
		return selectOne(vo);
	}

	
	/**
	 * (non-Javadoc)
	 *@Title: findById
	 *@Description: 
	 *@see com.sigmatrix.h5.dao.ProductDao#findById(java.lang.Integer, java.lang.String)
	 *@author youjun
	 *@date 2017年6月24日 下午8:05:48
	 */
	@Override
	public Product findById(final Integer id, final String enterpriseCode) throws DaoException {
		final StringBuilder sql = new StringBuilder("SELECT * FROM ").append(getTname(enterpriseCode, TABLE_NAME)).append(" WHERE _id = ?");
		final Object[] params = new Object[] { id };
		final List<Product> list = jdbcTemplate.query(sql.toString(), params, new ProductRowMapper());
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	/**
	 * (non-Javadoc)
	 *@Title: findListByCondition
	 *@Description: 
	 *@see com.sigmatrix.h5.dao.ProductDao#findListByCondition(com.sigmatrix.h5.entity.Product)
	 *@author youjun
	 *@date 2017年6月24日 下午8:06:00
	 */
	@Override
	public List<Product> findListByCondition(final Product product, final String enterpriseCode) throws DaoException {

		final StringBuilder sql = new StringBuilder("SELECT * FROM ").append(getTname(enterpriseCode, TABLE_NAME));
		final List<Object> paramList = new ArrayList<Object>();
		sql.append(" WHERE _status <> ?");
		paramList.add(Cons.STATUS_DELETE);
		try {
			sql.append(assemblyWhereConditon(product, paramList, true));
			return jdbcTemplate.query(sql.toString(), paramList.toArray(), new ProductRowMapper());
		} catch (DataAccessException e) {
			throw new DaoException(e);
		}
	}
	
	/**
	 * (non-Javadoc)
	 *@Title: findPartColumnListByCondition
	 *@Description: 
	 *@see com.sigmatrix.h5.dao.ProductDao#findPartColumnListByCondition(com.sigmatrix.h5.entity.Product)
	 *@author youjun
	 *@date 2017年6月24日 下午8:27:46
	 */
	@Override
	public List<ProductData> findPartColumnListByCondition(final Product product, final String enterpriseCode) throws DaoException {

		final StringBuilder sql = new StringBuilder()
		.append("SELECT _id, _code, _name, _pack_level, _norms_value, _norms_unit FROM ")
		.append(getTname(enterpriseCode, TABLE_NAME));
		final List<Object> paramList = new ArrayList<Object>();
		sql.append(" WHERE _status = ?");
		paramList.add(Cons.STATUS_ENABLE);
		sql.append(assemblyWhereConditon(product, paramList, true));
		try {
			return jdbcTemplate.query(sql.toString(), paramList.toArray(), new ProductDataRowMapper());
		} catch (DataAccessException e) {
			throw new DaoException(e);
		}
	}

	/**
	 *@Title: assemblyWhereConditon
	 *@Description: 组装where条件部分
	 *@return String
	 *@author youjun
	 *@date 2017年6月24日 下午8:26:21
	 *@param product
	 *@param paramList
	 *@param isExistWhereCondition 是否已经存在where条件,true则追加" AND ..."否则追加" WHERE 1=1"
	 *@throws DaoException
	 */
	private String assemblyWhereConditon(final Product product, 
			final List<Object> paramList, final boolean isExistWhereCondition) throws DaoException {
		
		if(paramList==null) {
			throw new DaoException("参数列表不能为null");
		}
		final StringBuilder whereSql = new StringBuilder();
		if(!isExistWhereCondition) {
			whereSql.append(" WHERE 1=1");
		}
		if(product!=null) {
			if(product.getCode()!=null) {
				whereSql.append(" AND _code = ?");
				paramList.add(product.getCode());
			}
			if(StringUtils.isNotBlank(product.getName())) {
				whereSql.append(" AND _name like ?");
				paramList.add("%"+product.getName()+"%");
			}
		}
		return whereSql.toString();
	}
	
	/**
	 * (non-Javadoc)
	 *@Title: findAllForSysn
	 *@Description: 
	 *@see com.sigmatrix.h5.dao.ProductDao#findAllForSysn(java.lang.String)
	 *@author 
	 *@date 2017年8月12日 下午4:58:53
	 */
	@Override
	public List<ProductData> findAllForSysn(final String eseCode) throws DaoException {
		final StringBuilder sql = new StringBuilder()
		.append("SELECT _id, _code, _name, _pack_level, _norms_value, _norms_unit FROM ")
		.append(getTname(eseCode, TABLE_NAME));
		sql.append(" WHERE _status = ").append(Cons.STATUS_ENABLE);
		logger.info(sql.toString());
		try {
			return jdbcTemplate.query(sql.toString(),new ProductDataRowMapper());
		} catch (DataAccessException e) {
			throw new DaoException(e);
		}
	}
	
	/**
	 *@ClassName: ProductDataRowMapper
	 *@Description: 分装返回实体
	 *@date 2017年8月12日 下午4:40:58
	 */
	public class ProductDataRowMapper implements RowMapper<ProductData> {
		public ProductData mapRow(final ResultSet resultSet, final int rowNum) throws SQLException {
			final ProductData product = new ProductData();
			product.setProductId(resultSet.getInt("_id"));
			product.setProductCode(resultSet.getString("_code"));
			product.setProductName(resultSet.getString("_name"));
			product.setNormsValue(resultSet.getDouble("_norms_value"));
			product.setNormsUnit(resultSet.getString("_norms_unit"));
			product.setProductUnit(resultSet.getShort("_pack_level"));
			return product;
		}
	}
	/**
	 * @ClassName: ProductRowMapper
	 * @Description: 封装返回的实体
	 * @author youjun 
	 * @date 2017-06-24 17:26:49
	 */
	public class ProductRowMapper implements RowMapper<Product> {
		public Product mapRow(final ResultSet resultSet, final int rowNum) throws SQLException {
			final Product product = new Product();
			product.setId(resultSet.getInt("_id"));
			product.setBasicModuleId(resultSet.getInt("_basic_module_id"));
			product.setCode(resultSet.getString("_code"));
			product.setName(resultSet.getString("_name"));
			product.setNormsValue(resultSet.getDouble("_norms_value"));
			product.setNormsUnit(resultSet.getString("_norms_unit"));
			product.setEnterpriseId(resultSet.getInt("_enterprise_id"));
			product.setCreatorId(resultSet.getInt("_creator_id"));
			product.setCreateTime(resultSet.getTimestamp("_create_time"));
			product.setUpdateId(resultSet.getInt("_update_id"));
			product.setUpdateTime(resultSet.getTimestamp("_update_time"));
			product.setEnableId(resultSet.getInt("_enable_id"));
			product.setEnableTime(resultSet.getTimestamp("_enable_time"));
			product.setDisableId(resultSet.getInt("_disable_id"));
			product.setDisableTime(resultSet.getTimestamp("_disable_time"));
			product.setStatus(resultSet.getShort("_status"));
			product.setCategory(resultSet.getInt("_category"));
			product.setPictures(resultSet.getString("_pictures"));
			product.setPicNum(resultSet.getInt("_pic_num"));
			product.setRemarks(resultSet.getString("_remarks"));
			product.setPackLevel(resultSet.getShort("_pack_level"));
			return product;
		}
	}
	/**
	 * (non-Javadoc)
	 *@Title: findByCode
	 *@Description: 
	 *@see com.sigmatrix.h5.dao.ProductDao#findByCode(java.lang.String, java.lang.String)
	 *@author gaomingkai
	 *@date 2017年12月26日 下午6:04:07
	 */
	@Override
	public Product findByCode(String code, String enterpriseCode) throws DaoException {
		final StringBuilder sql = new StringBuilder("SELECT * FROM ").append(getTname(enterpriseCode, TABLE_NAME))
				.append(" WHERE _status = ").append(Cons.STATUS_ENABLE)
				.append(" AND _code = ?");
		final Object[] params = new Object[] { code };
		final List<Product> list = jdbcTemplate.query(sql.toString(), params, new ProductRowMapper());
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}
	
	
	/**是否为分表策略,为true,表名加上传递的企业code*/
	public static final boolean ISSUBMETER = true;
	
	/**
	 *@Title: getEntTableName
	 *@Description: 根据表策略(分库/表)获得表名
	 *@return String
	 *@date 2017年7月13日 上午11:52:48
	 *@param eseCode
	 *@param tName
	 */
	protected String getTname(final String eseCode, final String tName) {
		
		final StringBuilder sb = new StringBuilder();
		if(ISSUBMETER) { // 分表
			if(Utils.isNotEmpty(eseCode)){//企业code不为空
				sb.append("_").append(eseCode);
			}
		}
		sb.append(tName);
		return sb.toString();
	}
	

}
